﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using QQ2564874169.Core;

namespace TestConsole
{
    public static class Utils
    {
        public static IEnumerable<Assembly> GetAssemblies(Func<string, bool> filter = null)
        {
            var assemblies = AppDomain.CurrentDomain.GetAssemblies().Select(i => i.Modules.First().ScopeName).ToList();
            var dir = AppDomain.CurrentDomain.BaseDirectory;
            if (Directory.Exists(dir) == false)
                dir = AppDomain.CurrentDomain.BaseDirectory;
            var files = Directory.GetFiles(dir, "*.dll");
            foreach (var file in files)
            {
                try
                {
                    var name = file.QQSplit(Path.DirectorySeparatorChar).Last();
                    if (assemblies.Any(i => i.Equals(name, StringComparison.OrdinalIgnoreCase)))
                        continue;
                    if (filter != null && filter(name) == false)
                        continue;
                    var assembly = Assembly.Load(File.ReadAllBytes(file));
                    assemblies.Add(assembly.Modules.First().ScopeName);
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex.Message);
                }
            }
            return AppDomain.CurrentDomain.GetAssemblies().Where(i =>
            {
                var name = i.Modules.First().ScopeName;
                return filter(name);
            });
        }
    }
}
